package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.enums.OrderStatusEnum;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.exception.NoStockException;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;

@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        /**
         * skuId: 1
         * wareId: 2
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            queryWrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(entities == null || entities.size() == 0){
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");

                if(info.getCode() == 0){
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){

            }


            wareSkuDao.insert(skuEntity);
        }else{
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> list=skuIds.stream().map(id->{
            SkuHasStockVo vo=new SkuHasStockVo();

            Long count=baseMapper.getSkuStock(id);
            vo.setSkuId(id);
            vo.setHasStock(count==null?false:count>0);

            return vo;
        }).collect(Collectors.toList());

        return list;
    }

    /**
     * 锁库存
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public boolean orderLockStock(WareSkuLockVo vo) {
        /**
         * 保存库存工作单详情信息
         * 追溯
         */
        WareOrderTaskEntity wareOrderTask=new WareOrderTaskEntity();
        wareOrderTask.setOrderSn(vo.getOrderSn());
        wareOrderTask.setCreateTime(new Date());
        wareOrderTaskService.save(wareOrderTask);

        //1、按照下单的收货地址，找到一个就近仓库，锁定库存
        //2、找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            skuWareHasStock.setSkuId(item.getSkuId());
            skuWareHasStock.setNum(item.getCount());

            //查询这个商品在哪个仓库有库存
            List<Long> wareIdList = wareSkuDao.listWareIdHasSkuStock(item.getSkuId());
            skuWareHasStock.setWareId(wareIdList);
            return skuWareHasStock;
        }).collect(Collectors.toList());

        //2、锁定库存
        for (SkuWareHasStock hasStock : collect) {
            boolean skuStocked = false;

            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            Integer stockNum = hasStock.getNum();

            if(wareIds==null || wareIds.size() <=0 ){
                //没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }

            for (Long wareId : wareIds) {
                //去库存表里锁库存
                //成功返回1，否则就是0
                Long res=wareSkuDao.lockSkuStock(skuId,wareId,stockNum);
                if(res ==1){
                    skuStocked=true;

                    WareOrderTaskDetailEntity orderTaskDetail=WareOrderTaskDetailEntity.builder()
                            .skuId(skuId)
                            .taskId(wareOrderTask.getId())
                            .wareId(wareId)
                            .skuNum(stockNum)
                            .lockStatus(1)
                            .build();
                    wareOrderTaskDetailService.save(orderTaskDetail);

                    //TODO 告诉MQ库存锁定成功,使用死信队列，在订单释放后，解锁库存。
                    StockLockedTo stockLockedTo=new StockLockedTo();
                    stockLockedTo.setId(wareOrderTask.getId());
                    StockDetailTo detailTo=new StockDetailTo();
                    BeanUtils.copyProperties(orderTaskDetail,detailTo);
                    stockLockedTo.setDetailTo(detailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockedTo);
                    break;
                }else{
                    //当前仓库锁失败，重试下一个仓库
                }
            }
            if(skuStocked==false){
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }

        return false;
    }

    /**
     * 1、库存自动解锁
     * 下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚。之前锁定的库存就要自动解锁
     * 2、订单失败
     * 锁库存失败
     *
     * 只要解锁库存的消息失败，一定要告诉服务器解锁失败。
     * @param to
     */
    @Override
    public void unLockStock(StockLockedTo to) {
        Long id = to.getId();//库存工作单的id
        StockDetailTo detailTo = to.getDetailTo();
        Long detailToId = detailTo.getId();
        /**
         * 解锁
         * 1、查询数据库关于这个订单的锁定库存信息
         * 有：证明库存锁定成功了
         *      解锁：订单情况
         *          1、没有这个订单，必须解锁
         *          2、有这个订单，不是解锁库存。
         *              订单状态：已取消，解锁库存
         *                      没取消，不能解锁
         *
         * 没有：库存锁定失败了，库存回滚了，这种情况无需解锁
         */
        //
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailToId);
        if (byId != null) {
            //需要解锁
            Long taskId = byId.getTaskId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(taskId);
            String orderSn = taskEntity.getOrderSn();
            //远程查询订单信息
            R r = orderFeignService.getOrderByOrderSn(orderSn);
            if (r.getCode() == 0) {
                OrderVo vo = r.getData("data", new TypeReference<OrderVo>() {
                });
                //判断订单状态是否已取消或者支付或者订单不存在
                if (vo == null || vo.getStatus() == OrderStatusEnum.CANCLED.getCode()) {
                    if(byId.getLockStatus()==1){
                        //当前库存工作单详情，状态1（已锁定），才能进行解锁
                        doUnLockStock(byId.getSkuId(), byId.getWareId(), byId.getSkuNum(), detailTo.getId());
                    }
                }
            } else {
                //远程调用失败
                //重新放入队列
                throw new RuntimeException("远程查询订单信息接口失败");
            }
        } else {
            //无需解锁，
        }
    }

    /**
     * 防止订单服务卡顿，导致订单状态消息一直改不了，库存优先到期，查订单状态新建，什么都不处理
     * 导致卡顿的订单，永远都不能解锁库存
     */
    @Override
    public void unLockStock(OrderTo to) {
        //查一下最新的库存解锁状态，防止重复解锁库存
        WareOrderTaskEntity taskEntity = wareOrderTaskService.getOrderTaskByOrderSn(to.getOrderSn());

        //按照工作单的id找到所有 没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> detailList = wareOrderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>()
                        .eq("task_id", taskEntity.getId())
                        .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity detail : detailList) {
            //真正去解锁库存
            doUnLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detail.getId());
        }
    }


    private void doUnLockStock(Long skuId, Long wareId, Integer skuNum, Long detailId) {
        //库存解锁
        this.wareSkuDao.unLockStock(skuId,wareId,skuNum);

        //更新工作单的状态
        WareOrderTaskDetailEntity detail=new WareOrderTaskDetailEntity();
        detail.setId(detailId);
        detail.setLockStatus(2);
        wareOrderTaskDetailService.updateById(detail);
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }
}